package com.wangtao.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class MyServer {

    public static void main(String[] args) {
        //创建BossGroup和WorkerGrroup
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGrroup = new NioEventLoopGroup(8);

        ServerBootstrap bootstrap = new ServerBootstrap();

        try {
            bootstrap.group(boosGroup,workerGrroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //使用http编解码器
                            pipeline.addLast(new HttpServerCodec());
                            //是以块方式写
                            pipeline.addLast(new ChunkedWriteHandler());
                            //HttpObjectAggregator将多个段聚合起来
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            //websocket 是以frame形式传递的 WebSocketServerProtocolHandler可以将http协议升级为ws协议（长连接）
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            pipeline.addLast(new MyTextWebSocketHandler());
                        }
                    });
            ChannelFuture cf = bootstrap.bind(8200).sync();

            System.out.println("服务端启动完成...");

            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            boosGroup.shutdownGracefully();
            workerGrroup.shutdownGracefully();
        }

    }
}
